# app/routes/user.py
from datetime import datetime
from bson import ObjectId, errors
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.utils.mongo import db

# 用户模型
class User:
    collection = db['users']
    
    @classmethod
    def create_or_update(cls, openid: str, user_info: dict = None):
        """创建或更新用户（微信登录后同步信息）"""
        # 基础数据（必传）
        user_data = {
            "openid": openid,
            "updated_at": datetime.now()
        }
        # 如果有用户信息（昵称、头像等），补充数据
        if user_info:
            user_data.update({
                "nickname": user_info.get("nickName", ""),
                "avatar_url": user_info.get("avatarUrl", ""),
                "gender": user_info.get("gender", 0),
                "country": user_info.get("country", ""),
                "province": user_info.get("province", ""),
                "city": user_info.get("city", "")
            })
        
        # 存在则更新，不存在则插入（原子操作）
        result = cls.collection.update_one(
            {"openid": openid},  # 查询条件
            {"$set": user_data},  # 更新内容
            upsert=True  # 不存在则插入
        )
        # 返回用户ID（新插入的ID或已存在的ID）
        if result.upserted_id:
            return result.upserted_id
        else:
            user = cls.collection.find_one({"openid": openid})
            return user["_id"] if user else None
    
    @classmethod
    def get_by_openid(cls, openid: str):
        """根据openid获取用户信息"""
        return cls.collection.find_one({"openid": openid})
    
    @classmethod
    def get_by_id(cls, user_id: str):
        """根据用户ID获取用户信息"""
        try:
            return cls.collection.find_one({"_id": ObjectId(user_id)})
        except errors.InvalidId:
            return None


# 蓝图路由定义 - 修改路由前缀
user_bp = Blueprint('user', __name__, url_prefix='/api/user')

# 用户统计接口
@user_bp.get('/stats/<user_id>')
@jwt_required()
def get_user_stats(user_id):
    try:
        current_user = get_jwt_identity()
        if current_user != user_id:
            return jsonify({"code": -1, "msg": "无权访问"}), 403
        
        # 获取打卡记录数量
        checkin_count = db.checkin_records.count_documents({"userId": user_id})
        
        # 获取反馈记录数量
        feedback_count = db.feedback_orders.count_documents({"userId": user_id})
        
        # 获取识别记录数量
        identify_count = db.identify_records.count_documents({"userId": user_id})
        
        return jsonify({
            "code": 0,
            "data": {
                "checkinCount": checkin_count,
                "feedbackCount": feedback_count,
                "identifyCount": identify_count
            }
        })
    except Exception as e:
        print(f"获取用户统计失败: {e}")
        return jsonify({"code": 1, "msg": "获取统计数据失败"})

# 最近反馈接口 - 修改路由路径
@user_bp.get('/feedback/recent')
@jwt_required()
def get_recent_feedback():
    try:
        user_id = get_jwt_identity()
        limit = int(request.args.get('limit', 3))
        
        # 直接从数据库获取最近的反馈记录
        feedbacks = list(db.feedback_orders.find({"userId": user_id})
                         .sort("createTime", -1)
                         .limit(limit))
        
        # 格式化返回数据
        formatted_feedbacks = []
        for fb in feedbacks:
            formatted_feedbacks.append({
                "id": str(fb.get("_id", "")),
                "buildingName": fb.get("buildingName", ""),
                "status": fb.get("status", ""),
                "createTime": fb.get("createTime", "").strftime('%Y-%m-%d %H:%M:%S') if fb.get("createTime") else ""
            })
        
        return jsonify({"code": 0, "data": formatted_feedbacks})
    except Exception as e:
        print(f"获取最近反馈失败: {e}")
        return jsonify({"code": 1, "msg": "获取最近反馈失败"})

# 最近打卡接口 - 修改路由路径
@user_bp.get('/checkin/recent')
@jwt_required()
def get_recent_checkins():
    try:
        user_id = get_jwt_identity()
        limit = int(request.args.get('limit', 3))
        
        # 直接从数据库获取最近的打卡记录
        checkins = list(db.checkin_records.find({"userId": user_id})
                       .sort("checkinTime", -1)
                       .limit(limit))
        
        # 格式化返回数据
        formatted_checkins = []
        for c in checkins:
            formatted_checkins.append({
                "id": str(c.get("_id", "")),
                "buildingName": c.get("buildingName", ""),
                "createTime": c.get("checkinTime", "").strftime('%Y-%m-%d %H:%M:%S') if c.get("checkinTime") else ""
            })
        
        return jsonify({"code": 0, "data": formatted_checkins})
    except Exception as e:
        print(f"获取最近打卡失败: {e}")
        return jsonify({"code": 1, "msg": "获取最近打卡失败"})

# 最近识别接口 - 修改路由路径
@user_bp.get('/identify/recent')
@jwt_required()
def get_recent_identifies():
    try:
        user_id = get_jwt_identity()
        limit = int(request.args.get('limit', 3))
        
        # 直接从数据库获取最近的识别记录
        identifies = list(db.identify_records.find({"userId": user_id})
                         .sort("createTime", -1)
                         .limit(limit))
        
        # 格式化返回数据
        formatted_identifies = []
        for i in identifies:
            formatted_identifies.append({
                "id": str(i.get("_id", "")),
                "buildingName": i.get("buildingName", i.get("targetName", "")),
                "result": i.get("result", ""),
                "createTime": i.get("createTime", "").strftime('%Y-%m-%d %H:%M:%S') if i.get("createTime") else ""
            })
        
        return jsonify({
            "code": 0,
            "data": formatted_identifies
        })
    except Exception as e:
        print(f"获取最近识别记录失败: {e}")
        return jsonify({"code": 1, "msg": "获取最近识别记录失败"})